package com.niit.chat.service.impl;

import com.niit.chat.mapper.MessageSessionMapper;
import com.niit.chat.service.MessageSessionService;
import com.niit.chat.vo.MessageSessionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 消息会话服务实现类
 */
@Service
public class MessageSessionServiceImpl implements MessageSessionService {

    @Autowired
    private MessageSessionMapper messageSessionMapper;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String REDIS_SESSION_KEY_PREFIX = "chat:session:";

    @Override
    public List<MessageSessionVO> getUserSessions(Long userId) {
        // 先尝试从Redis缓存获取
        String redisKey = REDIS_SESSION_KEY_PREFIX + userId;
        List<MessageSessionVO> cachedSessions = (List<MessageSessionVO>) redisTemplate.opsForValue().get(redisKey);
        
        if (cachedSessions != null) {
            return cachedSessions;
        }
        
        // 缓存未命中，从数据库查询
        List<MessageSessionVO> sessions = messageSessionMapper.getUserSessions(userId);
        
        // 将结果缓存到Redis，设置过期时间为5分钟
        redisTemplate.opsForValue().set(redisKey, sessions);
        redisTemplate.expire(redisKey, 300, java.util.concurrent.TimeUnit.SECONDS);
        
        return sessions;
    }

    @Override
    public MessageSessionVO getOrCreateSession(Long userId, Long friendId) {
        // 查询最近的一条消息
        MessageSessionVO session = messageSessionMapper.getSession(userId, friendId);
        
        if (session != null) {
            return session;
        } else {
            // 没有消息记录，创建一个空会话
            Map<String, Object> userInfo = messageSessionMapper.getUserInfo(friendId);
            
            MessageSessionVO newSession = new MessageSessionVO();
            newSession.setId(0L); // 临时ID
            newSession.setFriendId(friendId);
            newSession.setNickName((String) userInfo.get("nickname"));
            newSession.setAvatar((String) userInfo.get("avatar"));
            newSession.setLastMessage("");
            newSession.setLastMessageTime(LocalDateTime.now());
            
            return newSession;
        }
    }

    @Override
    public boolean deleteSession(Long sessionId, Long userId) {
        // 删除会话（逻辑删除）
        int rows = messageSessionMapper.deleteSession(sessionId, userId);
        
        // 清除Redis缓存
        String redisKey = REDIS_SESSION_KEY_PREFIX + userId;
        redisTemplate.delete(redisKey);
        
        return rows > 0;
    }
}